<?php

/**
 * 商家信息表
 */
use Common\Bridge;
use lib\core\AdminAction;
use Center\User;

define('SITE_AUTH', 'shop-info');
require('../../../common.inc.php');

class shopInfo extends AdminAction
{
    private $pdo_r;

    private $field = [
        'Id' => '店铺id',
        'CityId' => '所属城市id',
        'CateId' => '分类id',
        'Name' => '店铺名称',
        'Description' => '店铺描述',
        'Keywords' => '搜索用关键字',
        'Cover' => '店铺广告封面图',
        'UserId' => '管理用户ID',
        'Address' => '店铺地址',
        'Mobile' => '店铺电话',
        'Content' => '店铺内容',
        'Status' => [0 => '普通商家', 1 => '付费商家', 2 => '过期商家', 3 => '删除商家', 4 => '隐藏商家'],
        'UpdateTime' => '更新时间',
        'CreateTime' => '创建时间',
        'Members' => '会员数',
        'JCoin' => '扫码发放金果数',
        'Brower' => '浏览数'
    ];

    private $primary_key = 'Id';
    private $list_url = '/data/modules/shop/shopInfo.php';

    public function doDefault()
    {
        $param['Id'] = (int)$_GET['Id'];
        $param['Name'] = trim($_GET['Name']);
        $param['Mobile'] = trim($_GET['Mobile']);
        $param['CateId'] = (int)($_GET['CateId']);
        $param['Keywords'] = trim($_GET['Keywords']);

        $field = $this->field;
        $field_key = array_keys($field);
        $field_key_str = '`' . implode('`,`', $field_key) . '`';

        $page = empty($_GET['page']) ? 1 : (int)$_GET['page'];
        $limit = 20;
        $offset = ($page - 1) * $limit;

        $where = "1";
        if ($param['Id'] > 0) {
            $where .= " AND Id = " . $param['Id'];
        }
        if ($param['CateId'] > 0) {
            $where .= " AND CateId = " . $param['CateId'];
        }
        if ($param['Name'] != '') {
            $where .= " AND Name LIKE '%" . $param['Name'] . "%'";
        }

        if ($param['Mobile']) {
            $where .= " AND Mobile = '" . $param['Mobile'] . "'";
        }

        if ($param['Keywords']) {
            $where .= " AND Keywords = " . $param['Keywords'];
        }

        $primary_key = $this->primary_key;
        $count_sql = "SELECT COUNT($primary_key) AS `num` FROM `Shop` WHERE $where";

        $count = $this->readDb($count_sql);
        $count = (int)$count[0]['num'];

        $sql = "SELECT $field_key_str FROM `Shop` WHERE $where order by Sort DESC  LIMIT $offset,$limit";
        $data = $this->readDb($sql);

        $catedata = \Center\Category::getAllCate();
        $cate = $catedata['data'];
        $smarty = $this->app->page();
        if ($count > 0) {
            if (!empty($data)) {
                $smarty->value('list', $data);
            }

            $page_info['page'] = ceil($count / $limit);
            $page_info['count'] = $count;
            $smarty->value('page_info', $page_info);

            $pagination = $this->pagination($count, $limit, $page);
            $smarty->value('pagination', $pagination);
        }
        $city = [1 => '醴陵'];
        $smarty->value('cate', $cate);
        $smarty->value('city', $city);
        $smarty->value('param', $param);
        $smarty->value('field', $field);
        $smarty->output('shop/shopList.tpl');
    }

    /**
     * 上传图集
     */
    public function doAtlas()
    {
        $atlas = trim($_POST['atlas']);
        $files = $_FILES[$atlas];
        if (!empty($files)) {
            // 检测图片
//            $status = \Common\PhotoImage::checkImage($files, 0, 0, 2097152);
//            if ($status['code'] != 0) {
//                $this->_output(['status' => 201, 'msg' => $status['msg']]);
//            }

            $res = self::saveContentImg($files);
            if (!empty($res)) {
                $this->_output([
                    'status' => 200,
                    'msg' => '图片上传成功',
                    'data' => [
                        'img_url' => autohost($res), // url 访问地址
                        'file_name' => $atlas,
                    ]
                ], '__uploadAtlas');
            } else {
                $this->_output(['status' => 202, 'msg' => '上传失败！']);
            }
        } else {
            $this->_output(['status' => 203, 'msg' => '参数不正确！']);
        }
    }

    /**
     *
     */
    public function doEdit()
    {
        $id = (int)$_GET['Id'];
        if ($id < 1) {
            HDshowMsg('操作失败！', ['type' => 'error', 'desc' => 'Id为空']);
        }

        $sql = "SELECT * FROM Shop WHERE Id = $id";
        $list = $this->readDb($sql);

        $smarty = $this->app->page();
        $data = current($list);
        $catedata = \Center\Category::getAllCate();
        $cate = $catedata['data'];
        $data['Content'] = unserialize($data['Content']);
        $smarty->value('cate', $cate);
        $smarty->value('info', $data);
        $smarty->output('shop/shopedit.tpl');
    }

    public function doAdd()
    {
        $smarty = $this->app->page();
//        $smarty->value('info', current($list));
        $catedata = \Center\Category::getAllCate();
        $cate = $catedata['data'];
        $smarty->value('cate', $cate);
        $smarty->output('shop/shopadd.tpl');
    }

    public function doUpdate()
    {
        $id = intval($_POST['ShopId']);
        if (empty($id) || empty($_POST['Name'])) {
            HDshowMsg('缺少参数！', ['type' => 'error', 'url' => $this->list_url]);
        }

        //上传图片
        $img = $_FILES['Cover'];
        if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0) {
            // 复制图片
            $imgUrlAddre = self::saveImageUrl($id, $_FILES['Cover']);
        } else {
            $imgUrlAddre = false;
        }
        $atlas_img = $_POST['atlas1_img'];
        $atlas_txt = $_POST['atlas_text'];
        if (count($atlas_img) > 0) {
            foreach ($atlas_img as $k => $v) {
                $cont[$k] = [
                    'Text' => $atlas_txt[$k],
                    'ImgUrl' => $v
                ];
            }
        }

        $data = [
            'CityId' => intval($_POST['CityId']),
            'CateId' => intval($_POST['CateId']),
            'Name' => trim($_POST['Name']),
            'Keywords' => trim($_POST['Keywords']),
            'Description' => trim($_POST['Description']),
            'UserId' =>  intval($_POST['UserId']),
            'ActiveId' =>  intval($_POST['ActiveId']),
            'Address' => trim($_POST['Address']),
            'Mobile' => trim($_POST['Mobile']),
            'Content' => serialize($cont),
            'Sort' => intval($_POST['Sort']),
            'Status' => intval($_POST['Status']),
            'MaxJCoin' => intval($_POST['MaxJCoin']),
            'Brower' => intval($_POST['Brower']),
            'Abscissa' => trim($_POST['Abscissa']),
            'Ordinate' => trim($_POST['Ordinate']),
            'UpdateTime' => date('Y-m-d H:i:s'),
        ];

        if ($imgUrlAddre !== false) {
            $data['Cover'] = $imgUrlAddre;
        }
        $rel = Center\Shop::update($id, $data);
        if ($rel) {
            User::update(intval($_POST['UserId']), ['IsShop' => 1, 'ShopId' => $id]);
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    public function doInput()
    {
        if (empty($_POST['Name'])) {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }

        $data = [
            'CityId' => intval($_POST['CityId']),
            'CateId' => intval($_POST['CateId']),
            'Name' => trim($_POST['Name']),
            'Keywords' => trim($_POST['Keywords']),
            'Description' => trim($_POST['Description']),
            'UserId' =>  intval($_POST['UserId']),
            'ActiveId' =>  intval($_POST['ActiveId']),
            'Address' => trim($_POST['Address']),
            'Mobile' => trim($_POST['Mobile']),
            'Content' => trim($_POST['Content']),
            'Sort' => intval($_POST['Sort']),
            'Status' => intval($_POST['Status']),
            'MaxJCoin' => intval($_POST['MaxJCoin']),
            'Brower' => intval($_POST['Brower']),
            'Abscissa' => trim($_POST['Abscissa']),
            'Ordinate' => trim($_POST['Ordinate']),
            'UpdateTime' => date('Y-m-d H:i:s'),
        ];
        $id = Center\Shop::add($data);
        if ($id !== false && $id > 0) {
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
        //上传图片
        $img = $_FILES['Cover'];
        if (isset($img['name']) && $img['error'] == 0 && $img['size'] > 0 && $id) {
            // 复制图片
            $imgUrlAddre = self::saveImageUrl($id, $_FILES['Cover']);
            \Center\Shop::update($id, ['Cover' => $imgUrlAddre]);
        }

        if ($id) {
            User::update(intval($_POST['UserId']), ['IsShop' => 1, 'ShopId' => $id]);
            HDshowMsg('修改成功！', ['type' => 'success', 'url' => $this->list_url]);
        } else {
            HDshowMsg('修改失败！', ['type' => 'error', 'url' => $this->list_url]);
        }
    }

    /**
     * 利用SQL语句读取数据库并返回相应数据
     *
     * @param $sql
     * @return mixed
     */
    private function readDb($sql)
    {
        $pdo = $this->pdo_r;
        if (empty($pdo)) {
            $pdo = $this->pdo_r = Bridge::pdo(Bridge::DB_CENTER_W);
        }

        $obj = $pdo->query($sql);

        return $obj->fetchAll();
    }

    /**
     * @param $filename
     * @return bool|string
     */
    private static function saveImageUrl($id, $filename)
    {
        ///
        $upload_dir = \Common\ResourcePathManager::getShopImgSavePath();

        $hash = \Common\PhotoImage::getImageHash($id);
        //$src_img = $upload_dir . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg";
        $image_status = \Common\PhotoImage::checkImage($filename);

        if ($image_status['code'] == 4) {
            $image_status = \Common\PhotoImage::checkImageByUrl($filename);

            if ($image_status['code'] == 4) {
                return false;
            }
        }
        //配置图片上传目录
        $cfg = [
            'base' => $upload_dir,
            'thumb' => [
                'source' => [
                    'url' => '{hash1}/{hash2}/{id}.jpg'
                ],
                '150' => [
                    'width' => 150,
                    'height' => 150,
                    'position' => 'middle',
                    'watermark' => false,
                    'url' => '{hash1}/{hash2}/{id}_150x150.jpg'
                ],
                '300' => [
                    'width' => 300,
                    'position' => 'middle',
                    'watermark' => false,
                    'url' => '{hash1}/{hash2}/{id}_300.jpg'
                ],
                '800' => [
                    'width' => 800,
                    'position' => 'middle',
                    'watermark' => false,
                    'url' => '{hash1}/{hash2}/{id}_800.jpg'
                ]
            ],
            'hash1' => $hash['hash1'],
            'hash2' => $hash['hash2'],
            'id' => $id
        ];

        if ($image_status['status'] == true) {
            $result = \Common\PhotoImage::imageResize($cfg, $image_status);

            if ($result) {
                $res_arr = [
                    "http://img.jinguonet.com/shop/cover/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg",
                    "http://img.jinguonet.com/shop/cover/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_150x150.jpg",
                    "http://img.jinguonet.com/shop/cover/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_300.jpg",
                    "http://img.jinguonet.com/shop/cover/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_800.jpg"
                ];

                return "http://img.jinguonet.com/shop/cover/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg?v=" . time();
            }
        }

        return false;
    }

    /**
     * @param $filename
     * @return bool|string
     */
    private static function saveContentImg($filename)
    {
        ///
        $upload_dir = \Common\ResourcePathManager::getShopContentImgSavePath();
        list($msec, $sec) = explode(' ', microtime());
        $msectime =  (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);
        $id = $msectime;

        $hash = \Common\PhotoImage::getImageHash($id);
        //$src_img = $upload_dir . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg";
        $image_status = \Common\PhotoImage::checkImage($filename);

        if ($image_status['code'] == 4) {
            $image_status = \Common\PhotoImage::checkImageByUrl($filename);

            if ($image_status['code'] == 4) {
                return false;
            }
        }
        $date = date('Ymd');
        //配置图片上传目录
        $cfg = [
            'base' => $upload_dir,
            'thumb' => [
                'source' => [
                    'url' => '{date}/{hash1}/{hash2}/{id}.jpg'
                ],
                '300' => [
                    'width' => 300,
                    'position' => 'middle',
                    'watermark' => false,
                    'url' => '{date}/{hash1}/{hash2}/{id}_300.jpg'
                ]
            ],
            'hash1' => $hash['hash1'],
            'hash2' => $hash['hash2'],
            'date' => $date,
            'id' => $id
        ];

        if ($image_status['status'] == true) {
            $result = \Common\PhotoImage::imageResize($cfg, $image_status);

            if ($result) {
                $res_arr = [
                    "http://img.jinguonet.com/shop/content/" . $date . "/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg",
                    "http://img.jinguonet.com/shop/content/" . $date . "/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . "_300.jpg"
                ];

                return "http://img.jinguonet.com/shop/content/" . $date . "/" . $hash['hash1'] . "/" . $hash['hash2'] . "/" . $id . ".jpg";
            }
        }

        return false;
    }

    /**
     * 图片上传 js回调函数输出
     */
    private function _output($result, $callback = '_uploadImg')
    {
        $result = json_encode($result);
        exit('<script type="text/javascript">parent.' . $callback . '(\'' . $result . '\')</script>');
    }
}

$app->run();